﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BareWeb.BuiltWithFiddler.Extensions
{
    public partial class BuiltWithTechnologyControl : UserControl
    {
        public BuiltWithTechnologyControl(string techName, string url, string description, string statisticsUrl, string websitesUsingUrl) : this()
        {
            llTechnology.Text = techName;
            llTechnology.Links.Add(0, llTechnology.Text.Length, url);
            llTechnology.LinkClicked += linkGeneral_LinkClicked;

            llWebsitesUsing.Text = "Websites using " + techName;
            llWebsitesUsing.Links.Add(0, llWebsitesUsing.Text.Length, websitesUsingUrl);
            llWebsitesUsing.LinkClicked += linkGeneral_LinkClicked;

            llUsageStatistics.Links.Add(0, llUsageStatistics.Text.Length, statisticsUrl);
            llUsageStatistics.LinkClicked += linkGeneral_LinkClicked;

            UpdateContent(description);
        }

        public BuiltWithTechnologyControl()
        {
            InitializeComponent();
        }

        private void linkGeneral_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
        }

        /// <summary>
        /// Updates the content.
        /// </summary>
        /// <param name="techName">Name of the tech.</param>
        private void UpdateContent(string techName)
        {
            wbContent.Navigate("about:blank");
            wbContent.Dock = DockStyle.Fill;

            wbContent.MaximumSize = new Size(0, 100);
            //webBrowser.ScrollBarsEnabled = false;

            HtmlDocument document = wbContent.Document;
            if (document != null)
            {
                document.Write(MakeWebDocument(techName));
                document.BackColor = this.BackColor;
                if (document.Body != null)
                    document.Body.Style += string.Format("margin:0px; padding:0px; font-family:Verdana; font-size:{0}pt;", this.Font.SizeInPoints);
            }

            wbContent.Visible = true;
        }

        /// <summary>
        /// Makes the web document.
        /// </summary>
        /// <param name="jsonElementValue">The json element value.</param>
        /// <returns></returns>
        private string MakeWebDocument(string jsonElementValue)
        {
            string unescaped = System.Text.RegularExpressions.Regex.Unescape(jsonElementValue);

            return string.Format("<html><body scroll=\"auto\">{0}</body></html>", unescaped);
        }
    }
}
